#include "operations_order.h"
#include "ui_operations_order.h"
#include "api.h"
#include <QMessageBox>
#include <QDateTime>
#include <QHBoxLayout>
#include <QPushButton>
#include <QTableWidgetItem>

operations_order::operations_order(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::operations_order)
    , m_api(nullptr)
{
    ui->setupUi(this);
    
    // 初始化API（使用单例模式）
    m_api = Api::getInstance();
    
    // 连接信号槽
    setupConnections();
    
    // 加载数据
    loadOrderData();
    
    // 更新统计信息
    updateStatistics();
}

operations_order::~operations_order()
{
    this->close();
    delete ui;
}

void operations_order::setupConnections()
{
    // 搜索相关
    connect(ui->searchButton, &QPushButton::clicked, this, &operations_order::on_searchButton_clicked);
    connect(ui->refreshButton, &QPushButton::clicked, this, &operations_order::on_refreshButton_clicked);
    connect(ui->statusComboBox, QOverload<const QString&>::of(&QComboBox::currentTextChanged),
            this, &operations_order::on_statusComboBox_currentTextChanged);
    connect(ui->dateComboBox, QOverload<const QString&>::of(&QComboBox::currentTextChanged),
            this, &operations_order::on_dateComboBox_currentTextChanged);
    connect(ui->typeComboBox, QOverload<const QString&>::of(&QComboBox::currentTextChanged),
            this, &operations_order::on_typeComboBox_currentTextChanged);
    
    // 分页相关
    connect(ui->firstPageBtn, &QPushButton::clicked, this, &operations_order::on_firstPageBtn_clicked);
    connect(ui->prevPageBtn, &QPushButton::clicked, this, &operations_order::on_prevPageBtn_clicked);
    connect(ui->nextPageBtn, &QPushButton::clicked, this, &operations_order::on_nextPageBtn_clicked);
    connect(ui->lastPageBtn, &QPushButton::clicked, this, &operations_order::on_lastPageBtn_clicked);
}

void operations_order::loadOrderData()
{
    QJsonObject params;
    params["page"] = currentPage;
    params["pageSize"] = recordsPerPage;
    
    m_api->getOrders(params, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        // qDebug()<<response<<' '<<success;
        if (success) {
            QJsonArray orders = response["data"]["orders"].toArray();
            totalRecords = response["totalCount"].toString().toInt();
            calculateTotalPages();
            updateOrderTable(orders);
            updatePageButtons();
        } else {
            QMessageBox::critical(this, "错误", "加载订单数据失败：" + errorMsg);
            qDebug() << "加载订单数据失败:" << errorMsg;
        }
    });
}

void operations_order::updateOrderTable(const QJsonArray& orders)
{
    ui->orderTable->setRowCount(0);
    
    for (int i = 0; i < orders.size(); ++i) {
        QJsonObject order = orders[i].toObject();
        int row = ui->orderTable->rowCount();
        ui->orderTable->insertRow(row);
        
        ui->orderTable->setItem(row, 0, new QTableWidgetItem(order["order_id"].toString()));
        ui->orderTable->setItem(row, 1, new QTableWidgetItem(order["username"].toString()));
        ui->orderTable->setItem(row, 2, new QTableWidgetItem(order["ticket_type"].toString()));
        ui->orderTable->setItem(row, 3, new QTableWidgetItem(order["ticket_id"].toString()));
        ui->orderTable->setItem(row, 4, new QTableWidgetItem("¥" + order["amount"].toString()));
        ui->orderTable->setItem(row, 5, new QTableWidgetItem(order["status"].toString()));
        ui->orderTable->setItem(row, 6, new QTableWidgetItem(order["departure_time"].toString()));
        ui->orderTable->setItem(row, 7, new QTableWidgetItem(order["arrival_time"].toString()));
        ui->orderTable->setItem(row, 8, new QTableWidgetItem(order["departure_location"].toString()));
        ui->orderTable->setItem(row, 9, new QTableWidgetItem(order["arrival_location"].toString()));
        
        // 添加操作按钮
        QWidget* buttonWidget = new QWidget();
        QHBoxLayout* layout = new QHBoxLayout(buttonWidget);
        layout->setContentsMargins(5, 2, 5, 2);
        
        QPushButton* viewBtn = new QPushButton("查看");
        QPushButton* editBtn = new QPushButton("退票");
        QPushButton* deleteBtn = new QPushButton("删除");
        
        viewBtn->setMaximumWidth(50);
        editBtn->setMaximumWidth(50);
        deleteBtn->setMaximumWidth(50);
        
        // 设置删除按钮样式为红色以示区别
        deleteBtn->setStyleSheet("QPushButton { background-color: #ff4444; color: white; }"
                                "QPushButton:hover { background-color: #cc0000; }");
        
        // 连接按钮点击事件
        QString orderId = order["order_id"].toString();
        connect(viewBtn, &QPushButton::clicked, [this, orderId]() {
            onViewOrderClicked(orderId);
        });
        connect(editBtn, &QPushButton::clicked, [this, orderId]() {
            onRefundOrderClicked(orderId);
        });
        connect(deleteBtn, &QPushButton::clicked, [this, orderId]() {
            onDeleteOrderClicked(orderId);
        });
        
        layout->addWidget(viewBtn);
        layout->addWidget(editBtn);
        layout->addWidget(deleteBtn);
        
        ui->orderTable->setCellWidget(row, 10, buttonWidget);
    }
}

void operations_order::updatePageButtons()
{
    ui->pageLabel->setText(QString("第 %1 页，共 %2 页").arg(currentPage).arg(totalPages));
    
    ui->firstPageBtn->setEnabled(currentPage > 1);
    ui->prevPageBtn->setEnabled(currentPage > 1);
    ui->nextPageBtn->setEnabled(currentPage < totalPages);
    ui->lastPageBtn->setEnabled(currentPage < totalPages);
}

void operations_order::calculateTotalPages()
{
    totalPages = (totalRecords + recordsPerPage - 1) / recordsPerPage;
    if (totalPages < 1) totalPages = 1;
}

void operations_order::updateStatistics()
{
    m_api->getOrderStatistics([this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success) {
            QJsonObject stats = response["data"]["statistics"].toObject();
            
            ui->totalOrdersLabel->setText(QString("总订单数：%1").arg(stats["totalOrders"].toString()));
            ui->todayOrdersLabel->setText(QString("今日订单：%1").arg(stats["todayOrders"].toString()));
            ui->totalAmountLabel->setText(QString("总金额：¥%1").arg(stats["totalRevenue"].toString()));
        } else {
            qDebug() << "获取订单统计信息失败:" << errorMsg;
        }
    });
}

// 槽函数实现
void operations_order::on_searchButton_clicked()
{
    QString keyword = ui->searchEdit->text().trimmed();
    QString status = ui->statusComboBox->currentText();
    QString dateFilter = ui->dateComboBox->currentText();
    QString ticketType = ui->typeComboBox->currentText();
    
    searchOrders(keyword, status, dateFilter, ticketType);
}

void operations_order::on_refreshButton_clicked()
{
    saveAndRefreshData();
}

void operations_order::on_statusComboBox_currentTextChanged(const QString &text)
{
    (void)text;
    on_searchButton_clicked();
}

void operations_order::on_dateComboBox_currentTextChanged(const QString &text)
{
    (void)text;
    on_searchButton_clicked();
}

void operations_order::on_typeComboBox_currentTextChanged(const QString &text)
{
    (void)text;
    on_searchButton_clicked();
}

void operations_order::on_firstPageBtn_clicked()
{
    currentPage = 1;
    loadOrderData();
}

void operations_order::on_prevPageBtn_clicked()
{
    if (currentPage > 1) {
        currentPage--;
        loadOrderData();
    }
}

void operations_order::on_nextPageBtn_clicked()
{
    if (currentPage < totalPages) {
        currentPage++;
        loadOrderData();
    }
}

void operations_order::on_lastPageBtn_clicked()
{
    currentPage = totalPages;
    loadOrderData();
}

void operations_order::searchOrders(const QString &keyword, const QString &status, const QString &dateFilter, const QString &ticketType)
{
    QJsonObject params;
    params["searchText"] = keyword;
    params["status"] = status;
    params["dateFilter"] = dateFilter;
    params["type"] = ticketType;
    params["page"] = currentPage;
    params["pageSize"] = recordsPerPage;
    
    m_api->getOrders(params, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success && response.contains("orders")) {
            QJsonArray orders = response["orders"].toArray();
            totalRecords = response["totalCount"].toString().toInt();
            calculateTotalPages();
            updateOrderTable(orders);
            updatePageButtons();
        } else {
            QMessageBox::critical(this, "错误", "搜索订单失败：" + errorMsg);
            qDebug() << "搜索订单失败:" << errorMsg;
        }
    });
}

void operations_order::refreshData()
{
    currentPage = 1;
    loadOrderData();
    updateStatistics();
}

bool operations_order::saveOrderData()
{
    // 这里可以添加具体的数据保存逻辑
    // 例如：保存表格中被修改的订单状态、票种ID等信息
    // 目前作为示例，我们假设所有数据都是有效的
    
    // 遍历表格中的所有行，检查是否有需要保存的数据修改
    for (int row = 0; row < ui->orderTable->rowCount(); ++row) {
        QString orderId = ui->orderTable->item(row, 0)->text();
        QString currentStatus = ui->orderTable->item(row, 5)->text();
        
        // 检查状态是否需要更新（例如：从"待支付"改为"已支付"）
        // 这里可以根据实际业务需求添加更复杂的逻辑
        QJsonObject params;
        params["order_id"] = orderId;
        params["status"] = currentStatus;
        
        // 异步更新订单状态
        m_api->updateOrder(params, [this, orderId](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            if (!success) {
                qDebug() << "更新订单" << orderId << "失败:" << errorMsg;
            }
        });
    }
    
    qDebug() << "订单数据保存请求已发送";
    return true;
}

void operations_order::saveAndRefreshData()
{
    // 先保存数据到数据库
    if (saveOrderData()) {
        // 保存成功后刷新界面
        refreshData();
        QMessageBox::information(this, "成功", "数据已保存并刷新！");
    } else {
        QMessageBox::critical(this, "错误", "保存数据失败，请检查数据有效性！");
    }
}

void operations_order::onViewOrderClicked(const QString& orderId)
{
    // 查看订单详情
    QMessageBox::information(this, "订单详情", "查看订单：" + orderId + "\n\n功能开发中...");
}

void operations_order::onRefundOrderClicked(const QString& orderId)
{
    // 退票处理
    int ret = QMessageBox::question(this, "确认退票", 
                                   "确定要退订单 " + orderId + " 吗？",
                                   QMessageBox::Yes | QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        QJsonObject params;
        params["order_id"] = orderId;
        params["status"] = "已退票";
        
        m_api->updateOrder(params, [this, orderId](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            if (success) {
                QMessageBox::information(this, "成功", "订单 " + orderId + " 退票成功！");
                refreshData();
            } else {
                QMessageBox::critical(this, "错误", "退票失败：" + errorMsg);
            }
        });
    }
}

void operations_order::onDeleteOrderClicked(const QString& orderId)
{
    // 删除订单处理 - 添加更严格的确认对话框
    int ret = QMessageBox::warning(this, "确认删除", 
                                 "警告：您确定要删除订单 " + orderId + " 吗？\n\n"
                                 "此操作不可恢复，请谨慎操作！",
                                 QMessageBox::Yes | QMessageBox::No,
                                 QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        // 显示删除进度提示
        QMessageBox progressBox(this);
        progressBox.setWindowTitle("删除中");
        progressBox.setText("正在删除订单 " + orderId + "...");
        progressBox.setStandardButtons(QMessageBox::NoButton);
        progressBox.show();
        
        // 调用API删除订单
        m_api->deleteOrder(orderId, [this, orderId, &progressBox](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            progressBox.close();
            
            if (success) {
                QMessageBox::information(this, "删除成功", "订单 " + orderId + " 已成功删除！");
                // 刷新数据列表
                refreshData();
            } else {
                // 详细的错误处理
                QString detailedErrorMsg;
                if (statusCode == 404) {
                    detailedErrorMsg = "订单不存在或已被删除";
                } else if (statusCode == 403) {
                    detailedErrorMsg = "权限不足，无法删除此订单";
                } else if (statusCode == 500) {
                    detailedErrorMsg = "服务器内部错误，请稍后重试";
                } else {
                    detailedErrorMsg = errorMsg;
                }
                
                QMessageBox::critical(this, "删除失败", 
                                     "删除订单 " + orderId + " 失败！\n\n"
                                     "错误信息：" + detailedErrorMsg + "\n"
                                     "状态码：" + QString::number(statusCode));
            }
        });
    }
}
